package cmd

import (
	"ErgoGo/bootstrap"
	"ErgoGo/pkg/config"
	"ErgoGo/pkg/console"
	"ErgoGo/pkg/logger"
	"fmt"

	"github.com/gin-contrib/multitemplate"
	"github.com/gin-contrib/sessions"
	"github.com/gin-contrib/sessions/cookie"
	"github.com/gin-gonic/gin"
	"github.com/spf13/cobra"
)

var CmdServe = &cobra.Command{
	Use:   "serve",
	Short: "Start web server",
	Run:   runWeb,
	Args:  cobra.NoArgs,
}

func createMyRender() multitemplate.Renderer {
	r := multitemplate.NewRenderer()
	r.AddFromFiles("login", "storage/templates/login.html")
	r.AddFromFiles("dashboard", "storage/templates/layout.html", "storage/templates/dashboard.html")
	r.AddFromFiles("generate", "storage/templates/layout.html", "storage/templates/generate.html")
	r.AddFromFiles("history", "storage/templates/layout.html", "storage/templates/history.html")
	r.AddFromFiles("history_detail", "storage/templates/layout.html", "storage/templates/history_detail.html")
	r.AddFromFiles("settings", "storage/templates/layout.html", "storage/templates/settings.html")
	return r
}

func runWeb(cmd *cobra.Command, args []string) {
	gin.SetMode(gin.ReleaseMode)

	router := gin.New()

	// 配置会话
	store := cookie.NewStore([]byte("secret"))
	router.Use(sessions.Sessions("mysession", store))

	// 静态文件服务
	router.Static("/storage/static", "./storage/static")
	// 使用多模板
	router.HTMLRender = createMyRender()

	bootstrap.SetupRoute(router)

	console.Success(fmt.Sprintf("INFO Server running on [http://127.0.0.1:%s].\n", config.Get("app.port")))
	console.Warning("Press Ctrl+C to stop the server")

	err := router.Run(":" + config.Get("app.port"))
	if err != nil {
		logger.ErrorString("CMD", "serve", err.Error())
		console.Exit("Unable to start server, error:" + err.Error())
	}
}
